import 'dart:io';
import 'package:flutter/material.dart';
import '../../../common/style/app_style.dart';
import '../../../common/style/extension_util.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';

class MapSheetDialog extends StatefulWidget {
  const MapSheetDialog({super.key,this.lat,this.lon});
  final String? lat;
  final String? lon;
  @override
  State<MapSheetDialog> createState() => _MapSheetDialogState();
}

class _MapSheetDialogState extends State<MapSheetDialog> {
  List<(String,bool,int)> data = [
    ("高德地图",true,0),
    ("百度地图",true,1),
    ("腾讯地图",true,2),
  ];
  List<(String,bool,int)> realData = [];
  @override
  void initState() {
    handleMap();
    super.initState();
  }

  handleMap()async{
  bool aMap = await XMapNavigatorUtil.isAmapMapInstall();
  data[0] = (data[0].$1,aMap,0);
  bool bmap = await XMapNavigatorUtil.isBaiduMapInstall();
  data[1] = (data[1].$1,bmap,1);
  bool tenMap = await XMapNavigatorUtil.isTencentMapInstall();
  data[2] = (data[2].$1,tenMap,2);
  realData = data.where((element) => element.$2 == true).toList();
  setState(() {

  });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        ListView.separated(
          itemBuilder: (context, index) {
            return _buildItemMap(realData[index].$1,index);
          },
          shrinkWrap: true,
          itemCount: realData.length,
          separatorBuilder: (context, index) => const SizedBox(height: 0.5),
        ),
        if(realData.isEmpty)
  Container(

  width: double.infinity,
  height: 80,
  alignment: Alignment.center,
  decoration: const BoxDecoration(
  color: Colors.white),
  padding: EdgeInsets.symmetric(horizontal: 20),
  child: const Text("无地图,请去应用市场下载(高德、百度、腾讯地图任意一种)")),
        const SizedBox(
          height: 10,
        ),

       const Text("取消").addContainer(
              width: double.infinity,
              radius: 0,
              height: 40,
              alignment: Alignment.center,color: Colors.white,padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight,left: 20,right: 20)).addGestureTap(() {
                Navigator.pop(context);
  })
      ],
    ).addContainer(color: AppColor.backGroundColor);
  }

  _buildItemMap(String? name, int index) {
    return Container(

        width: double.infinity,
        height: 40,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: index == 0?  const BorderRadius.only(topLeft: Radius.circular(5),topRight: Radius.circular(5)) : null
        ),
        child: Text(name ?? "")).addGestureTap(() {
          var type = realData[index].$3;
          if(type == 0){
      XMapNavigatorUtil.gotoAMap(latitude: widget.lat,longitude: widget.lon);
  }else if(type == 1){
  XMapNavigatorUtil.gotoBaiduMap(latitude: widget.lat,longitude: widget.lon);
  }else{
  XMapNavigatorUtil.gotoTencentMap(latitude: widget.lat,longitude: widget.lon);
  }
  });
  }
}

class XMapNavigatorUtil {
  /// 高德地图导航
  static Future<bool> gotoAMap(
      {longitude, latitude, VoidCallback? toInstallCallBack}) {
    var url =
        '${Platform.isAndroid ? 'android' : 'ios'}amap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2';

    return gotoMap(
        url: url,
        toInstallCallBack: () {
          if (null != toInstallCallBack) {
            toInstallCallBack();
          }
        });
  }

  /// 腾讯地图导航
  static Future<bool> gotoTencentMap(
      {longitude, latitude, VoidCallback? toInstallCallBack}) async {
    var url =
        'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$latitude,$longitude&referer=IXHBZ-QIZE4-ZQ6UP-DJYEO-HC2K2-EZBXJ';

    return gotoMap(
        url: url,
        toInstallCallBack: () {
          if (null != toInstallCallBack) {
            toInstallCallBack();
          }
        });
  }

  /// 百度地图导航
  static Future<bool> gotoBaiduMap(
      {longitude, latitude, VoidCallback? toInstallCallBack}) async {
    var url =
        'baidumap://map/direction?destination=$latitude,$longitude&coord_type=gcj02&mode=driving';
    return gotoMap(
        url: url,
        toInstallCallBack: () {
          if (null != toInstallCallBack) {
            toInstallCallBack();
          }
        });
  }

  /// 跳转到第三方地图
  /// [url]跳转地址
  /// [toInstallCallBack]地图未安装回调
  static Future<bool> gotoMap(
      {required String url, VoidCallback? toInstallCallBack}) async {
    bool canLaunchUrl = await isMapInstall(url);

    if (!canLaunchUrl) {
      if (null != toInstallCallBack) {
        toInstallCallBack();
      }

      return false;
    }

    await launchUrl(Uri.parse(url));

    return true;
  }

  static void toInstallMap(String url) {
    launchUrl(Uri.parse(url));
  }

  static Future<bool> isBaiduMapInstall() {
    return canLaunchUrl(Uri.parse('baidumap://map/direction'));
  }

  static Future<bool> isTencentMapInstall() {
    return canLaunchUrl(Uri.parse('qqmap://map/routeplan'));
  }

  static Future<bool> isAmapMapInstall() {
    return canLaunchUrl(
        Uri.parse('${Platform.isAndroid ? 'android' : 'ios'}amap://navi'));
  }

  /// 判断地图是否有安装
  static Future<bool> isMapInstall(String url) {
    return canLaunchUrl(Uri.parse(url));
  }
}
